﻿using System;
using System.Linq;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using VPLink2013.Framework;
using VPLink2013.Framework.Constants;
using VPLink2013.Framework.Extensions;
using VPLink2014.Data;
using VPLink2014.Data.Notifications;

namespace VPLink2014
{
    public partial class ClearNotificationCounter : LayoutsPageBase
    {
        private string GetAbsPathDirectory()
        {
            string relativeDir = this.AppRelativeTemplateSourceDirectory
                         .Replace(@"~/_layouts", @"TEMPLATE/LAYOUTS")
                         .Replace(@"/", @"\");
            relativeDir = relativeDir.Substring(0, relativeDir.IndexOf("ApplicationPages"));
            return SPUtility.GetVersionedGenericSetupPath(relativeDir, 15);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string _appAbsPathDirectory = GetAbsPathDirectory();
            string tracePath = string.Format("{0}{1}", _appAbsPathDirectory, @"Trace");
            string responseJson = "{}";
            string userAccount = Context.User.Identity.Name;
            string workspaceName = this.Request.QueryString[QueryStringParam.WorkspaceName];
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (VPLinkLogConnection db = new VPLinkLogConnection())
                    {
                        Notification notifs = db.VplinkEntities.GetUserNotifications(userAccount);
                        if (notifs != null)
                        {
                            NotificationsItem userNotifications = FileSerialization.CreateObjFromXMLString<NotificationsItem>(notifs.XmlNotifications);
                            WorkSpace workspace = userNotifications.WorkSpaces.Where(x => x.Name.Equals(workspaceName)).FirstOrDefault();
                            if (workspace != null)
                            {
                                workspace.NewsSources
                                    .ForEach(source => source.listItems
                                        .ForEach(item => item.LastVisited = DateTime.Now.ToString()));
                                notifs.XmlNotifications = FileSerialization.CreateXmlStringFromObj(userNotifications);
                                db.VplinkEntities.SetUserNotification(notifs, false);
                            }
                        }
                    }
                });
                string res = "true";
                responseJson = string.Format(@"{{""success"" : ""{0}""}}", res.ToJson());
                Response.Write(responseJson);
                Response.End();
            }
            catch (System.Threading.ThreadAbortException)
            {
            }
            catch (Exception ex)
            {
                ContextTrace.AddTrace(string.Format("{0}", ex.Message));
                ContextTrace.AddTrace(string.Format("{0}", ex.StackTrace));
                responseJson = string.Format(@"{{""messageError"" : ""{0}"", ""stackTrace"" : ""{1}""}}", ex.Message.ToJson(), ex.StackTrace.ToJson());
                Response.Write(responseJson);
                Response.End();
            }
            ContextTrace.Save(tracePath,"clearnotifs_log");
        }
    }
}
